﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
using Windows.System.Threading;
using Thirteen23.TED.Data;

namespace Thirteen23.TED.Models
{
    public class TedTalksModel
    {
        private const string TedRssUrl = "http://www.ted.com/talks/rss";
        private readonly XNamespace mediaNamespace;
        private readonly XNamespace itunesNamespace;
        private static TedTalksModel _instance;
        private XDocument _lastDocument;
        private DateTime _lastDocumentFetch;

        public static TedTalksModel Instance
        {
            get
            {
                _instance = _instance ?? new TedTalksModel();
                return _instance;
            }
        }

        public List<TedTalk> Talks
        {
            get;
            private set;
        }

        public List<string> Categories
        {
            get;
            private set;
        }

        private TedTalksModel()
        {
            mediaNamespace = "http://search.yahoo.com/mrss/";
            itunesNamespace = "http://www.itunes.com/dtds/podcast-1.0.dtd";
        }

        public Task LoadTalksAsync()
        {
            return Task.Run(delegate()
            {
                XDocument rssFeed = null;

                if (DateTime.Now.Subtract(_lastDocumentFetch).TotalDays >= 0.5)
                {
                    rssFeed = XDocument.Load(TedRssUrl);

                    _lastDocument = rssFeed;
                    _lastDocumentFetch = DateTime.Now;
                }
                else
                {
                    rssFeed = _lastDocument;
                }

                Categories = rssFeed.Descendants("category").Select(item => item.Value).ToList();

                var posts = from item in rssFeed.Descendants("item")
                            select new TedTalk
                            {
                                Title = item.Element("title").Value,
                                Author = item.Element(itunesNamespace + "author").Value,
                                Description = item.Element("description").Value,
                                Date = DateTime.Parse(item.Element("pubDate").Value),
                                Category = item.Element("category").Value,
                                Url = item.Element("link").Value,
                                MediaLocation = item.Element(mediaNamespace + "content").Attribute("url").Value,
                                ImageLocation = item.Element(itunesNamespace + "image").Attribute("url").Value,
                                ThumbnailLocation = item.Element(mediaNamespace + "thumbnail").Attribute("url").Value
                            };

                Talks = posts.ToList();
            });
        }

    }
}
